package com.atguigu.gmall.interceptors;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.annotations.LoginRequired;
import com.atguigu.gmall.util.CookieUtil;
import com.atguigu.gmall.util.HttpclientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component // 把普通pojo实例化到spring容器中，相当于配置文件中的<bean id="" class=""/>
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 拦截代码
        // 判断被拦截的请求的访问方法的注解（是否需要拦截）
        HandlerMethod hm = (HandlerMethod) handler;
        LoginRequired methodAnnotation = hm.getMethodAnnotation(LoginRequired.class);

        // 是否拦截
        if(methodAnnotation == null){
            return true;
        }

        String token = "";
        // 从 cookie 中获取旧的令牌
        String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);
        if(StringUtils.isNotBlank(oldToken)){
            token = oldToken;
        }

        String newToken = request.getParameter("token");
        if(StringUtils.isNotBlank(newToken)){
            token = newToken;
        }

        // 是否必须登录
        boolean loginSuccess = methodAnnotation.loginSuccess(); // 获取请求是否必登录成功

        // 调用认证中心进行验证
        String success = "fail";
        if(StringUtils.isNotBlank(token)){
            Map<String, String> successMap = new HashMap<>();
            String ip = request.getHeader("x-forwarded-for");  // 通过nginx转发的客户端ip
            if(StringUtils.isBlank(ip)){
                ip = request.getRemoteAddr(); // 从request中获取ip
                if(StringUtils.isBlank(ip)){
                    ip = "127.0.0.1";
                }
            }
            String successJson = HttpclientUtil.doGet("http://passport.gmall.com:5002/verify?token=" + token + "&currentIp=" + ip);
            successMap = JSON.parseObject(successJson, Map.class);
            success = successMap.get("status");
        }

        if(loginSuccess){
            // 必须登录成功才能使用
            if(!success.equals("success")){
                // 重定向passport登录
                StringBuffer requestURL = request.getRequestURL();
                // requestURL是从前端js传过来的地址
                response.sendRedirect("http://passport.gmall.com:5002/index?ReturnUrl=" + requestURL);
                return false;
            }

            // 需要将token携带的用户信息写入
            request.setAttribute("memberId", "1");
            request.setAttribute("nickname", "nickname");

            // 认证通过，覆盖cookie中的token
            if(StringUtils.isNotBlank(token)){
                CookieUtil.setCookie(request, response, "oldToken", token, 60 * 60 * 2, true);
            }
        }else{
            // 没有登录也能用，但是必须验证
            if(success.equals("success")){
                // 需要将token携带的用户信息写入
                request.setAttribute("memberId", "1");
                request.setAttribute("nickname", "nickname");
                //验证通过，覆盖cookie中的token
                if(StringUtils.isNotBlank(token)){
                    CookieUtil.setCookie(request,response,"oldToken",token,60 * 60 * 2,true);
                }
            }
        }
        return true;
    }
}
